package com.km.app.controller.param;

import com.km.app.util.ImageTools;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;

public class CropState implements ParamState {

    private final static Log log = LogFactory.getLog(CropState.class);
    private Integer startX = 0;
    private Integer startY = 0;
    private Integer endX = 0;
    private Integer endY = 0;
    private String srcPath;
    private String targetPath;

    public CropState(String srcPath) {
        this.srcPath = srcPath == null ? null : srcPath.trim();
    }

    @Override
    public File action(ParamContext context) {
        String[] var1 = context.getQuery().split(",");
        if (var1 == null || var1.length == 0) {
            return null;
        }
        if (this.srcPath == null || this.srcPath.length() == 0) {
            return null;
        }
        for (String var2 : var1) {
            if (var2 == null || var2.trim().length() == 0) {
                continue;
            }
            String[] var3 = var2.split("_");
            if (var3 != null && var3.length == 2) {
                if (var3[0].equals("startX")) {
                    this.startX = Integer.valueOf(var3[1]);
                }
                if (var3[0].equals("startY")) {
                    this.startY = Integer.valueOf(var3[1]);
                }
                if (var3[0].equals("endX")) {
                    this.endX = Integer.valueOf(var3[1]);
                }
                if (var3[0].equals("endY")) {
                    this.endY = Integer.valueOf(var3[1]);
                }
            }
        }
        String var4 = this.srcPath.substring(0, this.srcPath.lastIndexOf("."));
        String var5 = this.srcPath.substring(this.srcPath.lastIndexOf("."));
        this.targetPath = var4 + "_crop_" + this.startX + "_" + this.startY + "_" + this.endX + "_" + this.endY;
        if (var5 != null) {
            targetPath += var5;
        }
        File f = new File(targetPath);
        if (f.exists()) {
            return f;
        }
        try {
            ImageTools.corpImageByCoordinate(this.srcPath, this.targetPath, this.startX, this.startY, this.endX, this.endY);
            return new File(this.targetPath);
        } catch (Exception e) {
            log.error(e);
            return null;
        }
    }
}
